<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-wrapper">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="配置类型">
            <el-input
              v-model="searchForm.configurationType"
              placeholder="请输入配置类型"
              clearable
              style="width: 220px"
            />
          </el-form-item>

          <el-form-item label="项目名称">
            <el-input 
              :model-value="selectedProject ? selectedProject.name : ''"
              placeholder="请选择项目"
              readonly
              class="selector-input"
              style="width: 220px"
            >
              <template #append>
                <el-button @click="openProjectSelector" v-permission="['increaseMachinePricing:view']">选择</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.activate"
              placeholder="请选择状态"
              clearable
              filterable
              style="width: 120px"
            >
              <el-option label="生效" :value="1" />
              <el-option label="失效" :value="0" />
            </el-select>
          </el-form-item>

          <el-form-item class="action-buttons">
            <el-button type="primary" @click="fetchData" class="search-btn" v-permission="['increaseMachinePricing:view']">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetForm" class="reset-btn" v-permission="['increaseMachinePricing:view']">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="showAddDialog" class="add-btn" v-permission="['increaseMachinePricing:edit']">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
            <el-button 
              type="danger" 
              @click="handleBatchDelete" 
              class="batch-delete-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['increaseMachinePricing:edit']"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="warning" 
              @click="handleBatchDeactivate" 
              class="batch-deactivate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['increaseMachinePricing:edit']"
            >
              <el-icon><Close /></el-icon>
              批量失效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="success" 
              @click="handleBatchActivate" 
              class="batch-activate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['increaseMachinePricing:edit']"
            >
              <el-icon><Check /></el-icon>
              批量生效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="primary" 
              @click="openBatchCopyDialog" 
              class="batch-copy-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['increaseMachinePricing:edit']"
            >
              <el-icon><CopyDocument /></el-icon>
              批量复制 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button type="success" @click="handleImport" class="import-btn" v-permission="['increaseMachinePricing:edit']">
              <el-icon><Upload /></el-icon>
              导入
            </el-button>
            <el-button type="info" @click="exportData" class="export-btn" v-permission="['increaseMachinePricing:view']">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button type="primary" @click="openExportDialog" class="custom-export-btn" v-permission="['increaseMachinePricing:view']">
              <el-icon><Setting /></el-icon>
              自定义导出
            </el-button>
            
            <!-- 隐藏的文件输入框 -->
            <input
              type="file"
              ref="fileInput"
              style="display: none"
              accept=".xlsx, .xls"
              @change="handleFileChange"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        border
        class="data-table"
        highlight-current-row
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" width="70" align="center"/>
        <el-table-column prop="activate" label="状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.activate ? 'success' : 'danger'">
            {{ scope.row.activate ? '生效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="project" label="项目名称" min-width="120" show-overflow-tooltip align="center"/>

        <el-table-column prop="configurationType" label="配置类型" min-width="120" show-overflow-tooltip align="center"/>
        <el-table-column prop="basicPrice" label="基础价格" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.basicPrice ? formatPrice(scope.row.basicPrice) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="pricePerMeter" label="每米价格" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.pricePerMeter ? formatPrice(scope.row.pricePerMeter) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="increaseLength" label="需求米数" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.increaseLength ? formatNumber(scope.row.increaseLength) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="核价" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.price ? formatPrice(scope.row.price) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="installationCosts" label="安装费" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.installationCosts ? formatPrice(scope.row.installationCosts) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="sum" label="合计价格" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.sum ? formatPrice(scope.row.sum) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="number" label="数量" min-width="80" align="right">
          <template #default="scope">
            {{ scope.row.number ? formatNumber(scope.row.number) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="总价" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.totalPrice ? formatPrice(scope.row.totalPrice) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="configuration" label="配置" min-width="120" show-overflow-tooltip align="center"/>
        <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
          <template #default="scope">
            {{ scope.row.createTime ? dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ scope.row.updateTime ? dayjs(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.updateName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="info" size="small" @click="showViewDialog(scope.row)" class="view-btn" :icon="View" v-permission="['increaseMachinePricing:view']">
                查看
              </el-button>
              <el-button type="primary" size="small" @click="showEditDialog(scope.row)" class="edit-btn" :icon="Edit" :disabled="scope.row.activate === 0" v-permission="['increaseMachinePricing:edit']">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="delete-btn" :icon="Delete" :disabled="scope.row.activate === 0" v-permission="['increaseMachinePricing:edit']">
                删除
              </el-button>
              <!-- <el-switch
                v-model="scope.row.activate"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                active-text="生效"
                inactive-text="失效"
                :active-value="1"
                :inactive-value="0"
                @change="activateChange($event === 1, scope.row.id)"
              /> -->
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="searchForm.page"
        v-model:page-size="searchForm.limit"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleClose"
      custom-class="increase-machine-pricing-dialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="increase-machine-pricing-form"
      >
        <el-card class="form-card" shadow="never">
          <template #header>
            <div class="form-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-form-item label="项目名称" prop="project">
            <el-select v-model="formData.project" placeholder="请选择项目名称" clearable filterable class="full-width">
              <el-option
                v-for="item in projectList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="配置类型" prop="configurationType">
            <el-input v-model="formData.configurationType" placeholder="请输入配置类型" />
          </el-form-item>
          <el-form-item label="基础价格" prop="basicPrice">
            <el-input 
              v-model="formData.basicPrice" 
              disabled 
              placeholder="从配置获取"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="每米价格" prop="pricePerMeter">
            <el-input 
              v-model="formData.pricePerMeter" 
              disabled 
              placeholder="从配置获取"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="需求米数" prop="increaseLength">
            <el-input v-model="formData.increaseLength" @input="handleValueChange" />
          </el-form-item>
          <el-form-item label="核价" prop="price">
            <el-input v-model="formData.price" disabled placeholder="自动计算" />
          </el-form-item>
          <el-form-item label="安装费" prop="installationCosts">
            <el-input v-model="formData.installationCosts" disabled placeholder="自动计算" />
          </el-form-item>
          <el-form-item label="合计价格" prop="sum">
            <el-input v-model="formData.sum" disabled placeholder="自动计算" />
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="formData.number" @input="handleValueChange" placeholder="请输入数量" />
          </el-form-item>
          <el-form-item label="总价" prop="totalPrice">
            <el-input v-model="formData.totalPrice" disabled placeholder="自动计算" />
          </el-form-item>
          <el-form-item label="配置" prop="configuration">
            <el-input
              v-model="formData.configuration"
              type="textarea"
              :rows="3"
              placeholder="请输入配置"
            />
          </el-form-item>
        </el-card>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看弹框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看提升机核价"
      width="600px"
      custom-class="increase-machine-pricing-dialog view-dialog"
    >
      <el-form
        :model="viewForm"
        label-width="120px"
        class="increase-machine-pricing-form"
      >
        <el-card class="form-card" shadow="never">
          <template #header>
            <div class="form-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-form-item label="项目名称">
            <el-input v-model="viewForm.project" disabled />
          </el-form-item>
          <el-form-item label="配置类型">
            <el-input v-model="viewForm.configurationType" disabled />
          </el-form-item>
          <el-form-item label="基础价格">
            <el-input v-model="viewForm.basicPrice" disabled />
          </el-form-item>
          <el-form-item label="每米价格">
            <el-input v-model="viewForm.pricePerMeter" disabled />
          </el-form-item>
          <el-form-item label="需求米数">
            <el-input v-model="viewForm.increaseLength" disabled />
          </el-form-item>
          <el-form-item label="核价">
            <el-input v-model="viewForm.price" disabled />
          </el-form-item>
          <el-form-item label="安装费">
            <el-input v-model="viewForm.installationCosts" disabled />
          </el-form-item>
          <el-form-item label="合计价格">
            <el-input v-model="viewForm.sum" disabled />
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="viewForm.number" disabled />
          </el-form-item>
          <el-form-item label="总价">
            <el-input v-model="viewForm.totalPrice" disabled />
          </el-form-item>
          <el-form-item label="配置">
            <el-input
              v-model="viewForm.configuration"
              type="textarea"
              :rows="3"
              disabled
            />
          </el-form-item>
        </el-card>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeViewDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自定义导出弹框 -->
    <el-dialog
      v-model="exportDialog.visible"
      title=""
      :width="680"
      custom-class="export-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <template #header>
        <div class="export-dialog-header">
          <div class="header-left">
            <el-icon class="header-icon"><Setting /></el-icon>
            <div>
              <div class="header-title">自定义导出设置</div>
              <div class="header-subtitle">选择您需要导出的数据字段</div>
            </div>
          </div>
          <div class="selected-count">
            已选择 {{ selectedExportFields.length }} / {{ exportFieldList.length }} 项
          </div>
        </div>
      </template>

      <div class="export-content">
        <div class="export-toolbar">
          <div class="toolbar-left">
            <el-button
              size="small"
              type="primary"
              @click="handleSelectAllFields(true)"
              :disabled="selectedExportFields.length === exportFieldList.length"
            >
              <el-icon><InfoFilled /></el-icon>
              全选
            </el-button>
            <el-button
              size="small"
              @click="handleSelectAllFields(false)"
              :disabled="selectedExportFields.length === 0"
            >
              <el-icon><Refresh /></el-icon>
              清空
            </el-button>
          </div>
          <div class="toolbar-right">
            <el-input
              v-model="fieldSearchText"
              size="small"
              placeholder="搜索字段..."
              clearable
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <div class="field-list-container">
          <div class="field-grid">
            <div
              v-for="field in filteredExportFields"
              :key="field.fieldName"
              class="field-card"
              :class="{ 'selected': selectedExportFields.includes(field.fieldName) }"
              @click="toggleField(field.fieldName)"
            >
              <div class="field-card-content">
                <el-checkbox
                  :model-value="selectedExportFields.includes(field.fieldName)"
                  @change="() => toggleField(field.fieldName)"
                  @click.stop=""
                  class="field-checkbox"
                />
                <div class="field-info">
                  <div class="field-name">{{ field.displayName }}</div>
                  <div class="field-key">{{ field.fieldName }}</div>
                </div>
                <div class="field-icon">
                  <el-icon v-if="selectedExportFields.includes(field.fieldName)" class="check-icon"><InfoFilled /></el-icon>
                </div>
              </div>
            </div>
          </div>

          <div v-if="filteredExportFields.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Search /></el-icon>
            <div class="empty-text">未找到匹配的字段</div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="export-footer">
          <div class="footer-info">
            <el-icon><InfoFilled /></el-icon>
            <span>将按当前查询条件导出选中字段的数据</span>
          </div>
          <div class="footer-buttons">
            <el-button @click="closeExportDialog" size="large">
              <el-icon><Delete /></el-icon>
              取消
            </el-button>
            <el-button
              type="primary"
              @click="confirmCustomExport"
              :loading="loading"
              size="large"
              :disabled="selectedExportFields.length === 0"
            >
              <el-icon><Download /></el-icon>
              导出 Excel
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 批量复制弹窗 -->
    <el-dialog 
      v-model="batchCopyVisible" 
      title="批量复制提升机核价" 
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-copy-content">
        <div class="copy-info">
          <el-icon class="info-icon"><InfoFilled /></el-icon>
          <span>即将复制 <strong>{{ selectedRows.length }}</strong> 条提升机核价记录到目标项目</span>
        </div>
        
        <div class="target-project-section">
          <label class="section-label">选择目标项目：</label>
          <div class="project-selector">
            <el-input
              :model-value="selectedTargetProject ? selectedTargetProject.name : ''"
              placeholder="请选择目标项目"
              readonly
              class="project-input"
            >
              <template #append>
                <el-button @click="openTargetProjectSelector">选择项目</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeBatchCopyDialog">取 消</el-button>
          <el-button type="primary" @click="confirmBatchCopy" :disabled="!selectedTargetProject">
            确定复制
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 目标项目选择器 -->
    <ArchiveSelector
      v-model="targetProjectSelectorVisible"
      title="选择目标项目"
      :fetch-data-api="getProjectListForBatchCopy"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      @confirm="handleTargetProjectSelect"
    />

    <!-- 文件上传组件（隐藏） -->
    <input
      ref="fileInput"
      type="file"
      accept=".xlsx,.xls"
      style="display: none"
      @change="handleFileChange"
    />

    <!-- 项目选择器组件 -->
    <ArchiveSelector v-model="projectSelectorVisible"
                     title="选择项目"
                     :search-fields="projectSearchFields"
                     :table-columns="projectTableColumns"
                     :fetch-data-api="getProjectListForSelector"
                     :multiple="false"
                     @confirm="handleProjectSelect" />
  </div>
</template>

<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { Search, Refresh, Plus, Edit, Delete, Document, InfoFilled, Setting, Upload, Download, View, Check, Close, CopyDocument } from '@element-plus/icons-vue'
import { getListApi, addApi,getPriceApi, editApi, deleteApi, batchDeleteApi, exportIncreaseMachinePricing, importIncreaseMachinePricing, downloadTemplate as downloadTemplateApi, updateStatusApi, batchUpdateStatusApi, getExportFieldsApi, exportCustomIncreaseMachinePricingApi, batchCopyApi } from '@/api/increaseMachinePricing/index.ts'
import { IncreaseMachinePricing, IncreaseMachinePricingBatchCopyDto } from '@/api/increaseMachinePricing/type.ts'
import dayjs from 'dayjs'
import { getSimpleProject, getSimpleProjectAll, getProjectDocumentListApi } from "@/api/project"; // 导入获取项目列表的API
import { ProjectDocument, ProjectDocumentListParam } from "@/api/project/type";
import ArchiveSelector from "@/components/common/ArchiveSelector.vue";
import { formatPrice, formatNumber } from '@/utils/formatter'; // 导入格式化工具
import { getListApi as getDictListApi } from '@/api/sysDictData'

// 定义类型
interface IncreaseMachinePricingListParam {
  page: number;
  limit: number;
  configurationType?: string;
  project?: string;
  configuration?: string;
  activate?: number;
}

interface ExportFieldInfo {
  fieldName: string;
  displayName: string;
}

// ----------------------- 组件状态定义 -----------------------
// 表格高度自适应
const tableHeight = ref(0)

// 可导出字段列表
const exportFieldList = ref<ExportFieldInfo[]>([
  { fieldName: 'configurationType', displayName: '配置类型' },
  { fieldName: 'basicPrice', displayName: '基础价格' },
  { fieldName: 'pricePerMeter', displayName: '每米价格' },
  { fieldName: 'increaseLength', displayName: '需求米数' },
  { fieldName: 'price', displayName: '核价' },
  { fieldName: 'installationCosts', displayName: '安装费' },
  { fieldName: 'sum', displayName: '合计价格' },
  { fieldName: 'number', displayName: '数量' },
  { fieldName: 'totalPrice', displayName: '总价' },
  { fieldName: 'project', displayName: '项目名称' },
  { fieldName: 'configuration', displayName: '配置' },
  { fieldName: 'createTime', displayName: '创建时间' }
])

// 自定义导出弹窗状态
const exportDialog = reactive({
  visible: false
})

// 选中的导出字段
const selectedExportFields = ref<string[]>([])

// 字段搜索文本
const fieldSearchText = ref('')

// 过滤后的导出字段列表
const filteredExportFields = computed(() => {
  if (!fieldSearchText.value) {
    return exportFieldList.value
  }
  return exportFieldList.value.filter(field =>
    field.displayName.toLowerCase().includes(fieldSearchText.value.toLowerCase()) ||
    field.fieldName.toLowerCase().includes(fieldSearchText.value.toLowerCase())
  )
})

// 切换字段选中状态
const toggleField = (fieldName: string) => {
  const index = selectedExportFields.value.indexOf(fieldName)
  if (index > -1) {
    selectedExportFields.value.splice(index, 1)
  } else {
    selectedExportFields.value.push(fieldName)
  }
}

// ----------------------- 表格相关 -----------------------
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)

// 批量删除相关
const selectedRows = ref<IncreaseMachinePricing[]>([])
const tableRef = ref()

// 项目选择器相关
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)
const selectedFormProject = ref<ProjectDocument | null>(null)

// 批量复制相关
const batchCopyVisible = ref(false)
const targetProjectSelectorVisible = ref(false)
const selectedTargetProject = ref<ProjectDocument | null>(null)

// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: [
      { value: 0, label: '进行中' },
      { value: 1, label: '已完成' },
      { value: 2, label: '已暂停' },
      { value: 3, label: '已取消' },
    ],
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 },
]

// 获取项目列表数据的API方法
const getProjectListForSelector = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 打开表单项目选择器
const openFormProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  searchForm.project = project.name
}

// 处理表单项目选择确认
const handleFormProjectSelect = (project: ProjectDocument) => {
  selectedFormProject.value = project
  formData.project = project.name || ''
}

const searchForm = reactive<IncreaseMachinePricingListParam>({
  page: 1,
  limit: 10,
  configurationType: '',
  project: '',
  configuration: '',
  activate: undefined
})

// 修改状态的参数
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 激活/失效状态切换
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return

  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({ id, activate: val ? 1 : 0 })
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const formData = reactive({
  id: undefined as number | undefined,
  configurationType: '进口',
  basicPrice: 125000,
  pricePerMeter: 4500,
  increaseLength: undefined as number | undefined,
  price: undefined as number | undefined,
  installationCosts: undefined as number | undefined,
  project: '',
  configuration: '',
  sum: undefined as number | undefined,
  number: undefined as number | undefined,
  totalPrice: undefined as number | undefined
})

const viewForm = reactive({
  id: undefined as number | undefined,
  configurationType: '',
  basicPrice: undefined as number | undefined,
  pricePerMeter: undefined as number | undefined,
  increaseLength: undefined as number | undefined,
  price: undefined as number | undefined,
  installationCosts: undefined as number | undefined,
  project: '',
  configuration: '',
  sum: undefined as number | undefined,
  number: undefined as number | undefined,
  totalPrice: undefined as number | undefined
})

const rules = {
  increaseLength: [
    { required: true, message: '请输入需求米数', trigger: 'blur' }
  ],
  project: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑提升机核价' : '新增提升机核价'
})

// ----------------------- 表格数据处理 ----------------------
// 定义项目接口类型
interface Project {
  id: number;
  name: string;
}
// 项目列表
const projectList = ref<Project[]>([])
// 获取项目列表
const getProjectList = async () => {
  try {
    const res = await getSimpleProject()
    if (res && res.data) {
      projectList.value = res.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 监听值变化
const handleValueChange = () => {
  calculateSum()
}

// 自动计算合计
const calculateSum = async () => {
  if(formData.increaseLength !== undefined && formData.basicPrice !== undefined && formData.pricePerMeter !== undefined){
    // 创建符合API要求的参数对象
    const apiParams = {
      ...formData,
      isDelete: 0,
      createTime: undefined,
      updateTime: undefined,
      createBy: undefined,
      updateBy: undefined
    } as IncreaseMachinePricing
    
    const res = await getPriceApi(apiParams)
    if(res && res.data){
      formData.price = res.data.price
      formData.installationCosts = res.data.installationCosts
      
      // 计算合计价格 (price + installationCosts)
      if(formData.price !== undefined && formData.installationCosts !== undefined) {
        formData.sum = Number((formData.price + formData.installationCosts).toFixed(2))
      }
      
      // 计算总价 (sum * number)
      if(formData.sum !== undefined && formData.number !== undefined && formData.number > 0) {
        formData.totalPrice = Number((formData.sum * formData.number).toFixed(2))
      }
    }
  }
}

const fetchData = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const response = await getListApi(searchForm)
    if (response.code === 200) {
      tableData.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  selectedProject.value = null
  searchForm.page = 1
  searchForm.limit = 10
  searchForm.configurationType = ''
  searchForm.project = ''
  searchForm.configuration = ''
  searchForm.activate = undefined
  fetchData()
}

// ----------------------- 新增/编辑表单相关 -----------------------
const formRef = ref<FormInstance>()

// 显示新增对话框
const showAddDialog = async () => {
  isEdit.value = false
  dialogVisible.value = true
  formData.id = undefined
  formData.configurationType = '进口'
  formData.increaseLength = undefined
  formData.price = undefined
  formData.installationCosts = undefined
  formData.project = ''
  formData.configuration = ''
  formData.sum = undefined
  formData.number = undefined
  formData.totalPrice = undefined
  
  // 从字典获取配置值
  await getDictData()
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 显示编辑对话框
const showEditDialog = (row: IncreaseMachinePricing) => {
  // 检查记录的状态
  if (row.activate === 0) {
    ElMessage.warning('该提升机核价已失效，不允许编辑')
    return
  }
  
  isEdit.value = true
  dialogVisible.value = true
  formData.id = row.id
  formData.configurationType = row.configurationType || ''
  formData.basicPrice = row.basicPrice || 0
  formData.pricePerMeter = row.pricePerMeter || 0
  formData.increaseLength = row.increaseLength
  formData.price = row.price
  formData.installationCosts = row.installationCosts
  formData.project = row.project || ''
  formData.configuration = row.configuration || ''
  formData.sum = row.sum
  formData.number = row.number
  formData.totalPrice = row.totalPrice
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 显示查看对话框
const showViewDialog = (row: IncreaseMachinePricing) => {
  viewDialogVisible.value = true
  Object.assign(viewForm, row)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 关闭查看对话框
const closeViewDialog = () => {
  viewDialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    // 创建提交数据，只包含必要字段
    const submitData = {
      ...formData,
      isDelete: 0,
      createTime: undefined,
      updateTime: undefined,
      createBy: undefined,
      updateBy: undefined
    } as IncreaseMachinePricing

    const api = isEdit.value ? editApi : addApi
    const response = await api(submitData)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      handleClose()
      fetchData()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// ----------------------- 删除相关 -----------------------
const handleDelete = async (row: IncreaseMachinePricing) => {
  // 检查记录的状态
  if (row.activate === 0) {
    ElMessage.warning('该提升机核价已失效，不允许删除')
    return
  }
  
  try {
    await ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteApi(row.id!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection: IncreaseMachinePricing[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  // 检查选中的记录中是否有已失效的
  const invalidRecords = selectedRows.value.filter(item => item.activate === 0)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许删除操作`)
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗?`, '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const ids = selectedRows.value.map(row => row.id!).filter(id => id)
    const response = await batchDeleteApi(ids)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      fetchData()
      // 清空选择
      tableRef.value?.clearSelection()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量失效
const handleBatchDeactivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要失效的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedRows.value.length}条记录设为失效吗？`, '批量失效确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id!).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 0 })
    ElMessage.success('批量失效成功')
    fetchData()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量失效失败:', error)
      ElMessage.error('批量失效失败')
    }
  }
}

// 批量生效
const handleBatchActivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要生效的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedRows.value.length}条记录设为生效吗？`, '批量生效确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id!).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 1 })
    ElMessage.success('批量生效成功')
    fetchData()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量生效失败:', error)
      ElMessage.error('批量生效失败')
    }
  }
}

// ----------------------- 批量复制相关 -----------------------
// 打开批量复制弹窗
const openBatchCopyDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要复制的记录')
    return
  }
  
  // 允许复制失效数据，复制后自动生效
  
  batchCopyVisible.value = true
}

// 关闭批量复制弹窗
const closeBatchCopyDialog = () => {
  batchCopyVisible.value = false
  selectedTargetProject.value = null
}

// 打开目标项目选择器
const openTargetProjectSelector = () => {
  targetProjectSelectorVisible.value = true
}

// 处理目标项目选择
const handleTargetProjectSelect = (project: ProjectDocument) => {
  selectedTargetProject.value = project
  console.log('选择的目标项目:', project)
}

// 获取项目列表(用于批量复制)
const getProjectListForBatchCopy = async (params: any) => {
  try {
    const queryParams: ProjectDocumentListParam = {
      page: params.page || 1,
      limit: params.limit || 10,
      name: params.name || '',
      code: params.code || '',
      customer: params.customer || '',
      status: params.status || ''
    }
    const res = await getProjectDocumentListApi(queryParams)
    // ArchiveSelector期望的数据格式
    return {
      data: {
        list: res.data?.list || [],
        total: res.data?.total || 0
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { 
      data: {
        list: [], 
        total: 0 
      }
    }
  }
}

// 确认批量复制
const confirmBatchCopy = async () => {
  if (!selectedTargetProject.value) {
    ElMessage.warning('请选择目标项目')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedRows.value.length}条提升机核价复制到项目"${selectedTargetProject.value.name}"吗？`, '批量复制确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const sourceIds = selectedRows.value.map(row => row.id).filter(id => id !== undefined) as number[]
    await batchCopyApi({
      sourceIds,
      targetProject: selectedTargetProject.value.name!
    })
    
    ElMessage.success(`成功复制${sourceIds.length}条提升机核价`)
    closeBatchCopyDialog()
    fetchData()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量复制失败:', error)
      ElMessage.error('批量复制失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  searchForm.limit = val
  searchForm.page = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  searchForm.page = val
  fetchData()
}

// ----------------------- 导入导出相关 -----------------------
const fileInput = ref<HTMLInputElement>()

// 导出数据
const exportData = async () => {
  try {
    loading.value = true
    searchForm.limit = 9999

    await exportIncreaseMachinePricing(searchForm)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 处理导入
const handleImport = () => {
  fileInput.value?.click()
}

// 文件选择变化
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 验证文件类型
  const validTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel'
  ]
  if (!validTypes.includes(file.type)) {
    ElMessage.error('请选择Excel文件')
    return
  }

  try {
    const response = await importIncreaseMachinePricing(file)
    if (response.code === 200) {
      ElMessage.success('导入成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    // 清空文件输入框
    target.value = ''
  }
}

// 下载模板
const downloadTemplate = async () => {
  try {
    await downloadTemplateApi()
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

// 打开自定义导出弹窗
const openExportDialog = async () => {
  try {
    // 获取可导出字段列表
    const res = await getExportFieldsApi()
    if (res && res.data) {
      exportFieldList.value = res.data
      // 默认选中所有字段
      selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
      exportDialog.visible = true
    }
  } catch (error) {
    console.error('获取导出字段失败:', error)
    ElMessage.error('获取导出字段失败')
  }
}

// 关闭自定义导出弹窗
const closeExportDialog = () => {
  exportDialog.visible = false
}

// 全选/取消全选导出字段
const handleSelectAllFields = (checked: boolean) => {
  if (checked) {
    selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
  } else {
    selectedExportFields.value = []
  }
}

// 确认自定义导出
const confirmCustomExport = async () => {
  if (selectedExportFields.value.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }

  try {
    loading.value = true
    // 移除分页参数，确保导出所有数据
    const { page, limit, ...exportParams } = searchForm
    
    // 检查是否有查询条件
    const hasConditions = Object.keys(exportParams).some(key => {
      const value = (exportParams as any)[key]
      return value !== undefined && value !== null && value !== ''
    })
    
    if (hasConditions) {
      console.log('自定义导出-按查询条件导出数据:', exportParams)
      ElMessage.info('正在导出符合当前查询条件的数据...')
    } else {
      console.log('自定义导出-导出全部数据')
      ElMessage.info('正在导出全部数据...')
    }
    
    // 调用自定义导出API，传递选中字段和查询条件
    await exportCustomIncreaseMachinePricingApi({
      fields: selectedExportFields.value,
      searchParam: exportParams as any
    })
    ElMessage.success('导出成功')
    closeExportDialog()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 获取字典配置值
const getDictData = async () => {
  try {
    // 获取基础价格字典
    const basicPriceRes = await getDictListApi({ 
      dictType: 'basic_price',
      page: 1,
      limit: 9999
    })
    if (basicPriceRes.code === 200 && basicPriceRes.data.list && basicPriceRes.data.list.length > 0) {
      // 取第一个配置值作为基础价格
      const basicPriceValue = parseFloat(basicPriceRes.data.list[0].dictValue)
      formData.basicPrice = basicPriceValue
    }
    
    // 获取每米价格字典
    const pricePerMeterRes = await getDictListApi({ 
      dictType: 'price_per_meter',
      page: 1,
      limit: 9999
    })
    if (pricePerMeterRes.code === 200 && pricePerMeterRes.data.list && pricePerMeterRes.data.list.length > 0) {
      // 取第一个配置值作为每米价格
      const pricePerMeterValue = parseFloat(pricePerMeterRes.data.list[0].dictValue)
      formData.pricePerMeter = pricePerMeterValue
    }
  } catch (error) {
    console.error('获取字典数据失败:', error)
  }
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
    getProjectList()
    getDictData()

  fetchData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped lang="scss">
.container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
  
  .search-wrapper {
    padding: 12px 20px;
  }
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
    
    .el-form-item {
      margin-bottom: 4px;
      margin-right: 16px;
      
      :deep(.el-form-item__label) {
        color: #606266;
        font-weight: 500;
        margin-bottom: 6px;
        font-size: 14px;
      }
      
      .el-select {
        .el-input__wrapper {
          border-radius: 6px;
          height: 34px;
          transition: all 0.3s ease;
          
          &:hover {
            box-shadow: 0 0 0 1px #409eff inset;
          }
        }
      }
      
      .el-input {
        .el-input__wrapper {
          border-radius: 6px;
          height: 34px;
          transition: all 0.3s ease;
          
          &:hover {
            box-shadow: 0 0 0 1px #409eff inset;
          }
        }
      }
      
      &.action-buttons {
        margin-left: auto;
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          padding: 6px 14px;
          font-size: 13px;
          transition: all 0.3s;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
          }
          
          .el-icon {
            margin-right: 6px;
          }
          
          &.search-btn {
            background: linear-gradient(135deg, #409eff, #1989fa);
            border: none;
            color: white;
            
            &:hover {
              opacity: 0.9;
            }
          }
          
          &.reset-btn {
            background: linear-gradient(135deg, #f56c6c, #f78989);
            border: none;
            color: white;
            
            &:hover {
              opacity: 0.9;
            }
          }
          
          &.add-btn {
            background: linear-gradient(135deg, #67c23a, #85ce61);
            border: none;
            color: white;
            
            &:hover {
              opacity: 0.9;
            }
          }
          
          &.batch-delete-btn {
            background: linear-gradient(135deg, #f56c6c, #f78989);
            border: none;
            color: white;
            
            &:hover:not(:disabled) {
              opacity: 0.9;
            }
            
            &:disabled {
              background: #c0c4cc;
              opacity: 0.6;
              cursor: not-allowed;
            }
          }
          
          &.import-btn {
            background: linear-gradient(135deg, #67c23a, #85ce61);
            border: none;
            color: white;
            
            &:hover {
              opacity: 0.9;
            }
          }
          
          &.export-btn {
            background: linear-gradient(135deg, #909399, #a6a9ad);
            border: none;
            color: white;
            
            &:hover {
              opacity: 0.9;
            }
          }
          
          &.custom-export-btn {
            background: linear-gradient(135deg, #409eff, #1989fa);
            border: none;
            color: white;
            
            &:hover {
              opacity: 0.9;
            }
          }
        }
      }
    }
  }
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  height: calc(100vh - 200px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 8px;
  overflow: hidden;
  flex: 1;
  
  :deep(.el-table) {
    border-radius: 8px;
    
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: #f8fafc;
          color: #606266;
          font-weight: 600;
          border-bottom: 1px solid #e4e7ed;
        }
      }
    }
    
    .el-table__body-wrapper {
      .el-table__body {
        tr:hover {
          background-color: #f8fafc;
        }
      }
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 8px;

    .el-button {
      padding: 6px 12px;
      transition: all 0.3s;
      border-radius: 6px;
      font-size: 12px;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
    }
  }
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
  background: #fff;
  border-radius: 0 0 12px 12px;
  
  :deep(.el-pagination) {
    .el-pagination__total,
    .el-pagination__jump {
      color: #606266;
    }
    
    .el-pager li {
      border-radius: 6px;
      margin: 0 2px;
      
      &.is-active {
        background: linear-gradient(135deg, #409eff, #1989fa);
        color: white;
      }
    }
    
    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}

.increase-machine-pricing-form {
  padding: 20px;

  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;

    &:last-child {
      margin-bottom: 0;
    }

    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }

    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #67c23a;
      }
    }
  }

  :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
  }

  :deep(.el-input) {
    .el-input__inner {
      transition: all 0.3s;

      &:hover, &:focus {
        border-color: #67c23a;
      }
    }
  }

  :deep(.el-button--primary) {
    background-color: #67c23a;
    border-color: #67c23a;

    &:hover {
      opacity: 0.9;
    }
  }
}

:deep(.increase-machine-pricing-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
    margin-right: 0;

    .el-dialog__title {
      color: #67c23a;
      font-weight: 600;
    }
  }

  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
  }
}

.view-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;

    .el-dialog__title {
      color: #409EFF;
      font-weight: 600;
    }
  }
}

// 批量复制弹窗样式
.batch-copy-content {
  padding: 20px 0;
  
  .copy-info {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 24px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #409EFF;
    
    .info-icon {
      color: #409EFF;
      font-size: 18px;
    }
    
    span {
      color: #606266;
      font-size: 14px;
      
      strong {
        color: #409EFF;
        font-weight: 600;
      }
    }
  }
  
  .target-project-section {
    .section-label {
      display: block;
      margin-bottom: 8px;
      color: #606266;
      font-size: 14px;
      font-weight: 500;
    }
    
    .project-selector {
      .project-input {
        .el-input__wrapper {
          border-radius: 6px;
        }
        
        .el-input-group__append {
          background-color: #f5f7fa;
          border-color: #dcdfe6;
          
          .el-button {
            background: transparent;
            border: none;
            color: #409EFF;
            
            &:hover {
              background-color: rgba(64, 158, 255, 0.1);
            }
          }
        }
      }
    }
  }
}

// 自定义导出弹窗样式
:deep(.export-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

  .el-dialog__header {
    padding: 0;
    margin-right: 0;
    border-bottom: none;
  }

  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__footer {
    padding: 0;
    border-top: none;
  }
}

.export-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 20px;
  color: white;
  // background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .header-icon {
      font-size: 28px;
      background: rgba(255, 255, 255, 0.2);
      padding: 12px;
      border-radius: 50%;
      backdrop-filter: blur(10px);
    }

    .header-title {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .header-subtitle {
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .selected-count {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
}

.export-content {
  padding: 24px;

  .export-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #f8fafc;
    border-radius: 10px;
    border: 1px solid #e2e8f0;

    .toolbar-left {
      display: flex;
      gap: 12px;

      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        &:disabled {
          transform: none;
          box-shadow: none;
        }
      }
    }

    .toolbar-right {
      :deep(.el-input) {
        .el-input__wrapper {
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
          border: 1px solid #e2e8f0;
          transition: all 0.3s;

          &:hover, &.is-focus {
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
          }
        }
      }
    }
  }

  .field-list-container {
    .field-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;

        &:hover {
          background: #94a3b8;
        }
      }
    }

    .field-card {
      background: white;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 16px;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

      &:hover {
        border-color: #667eea;
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
      }

      &.selected {
        border-color: #667eea;
        background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
        box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);

        .field-card-content {
          .field-name {
            color: #667eea;
            font-weight: 600;
          }

          .field-key {
            color: #4c51bf;
          }
        }
      }

      .field-card-content {
        display: flex;
        align-items: center;
        gap: 12px;

        .field-checkbox {
          flex-shrink: 0;

          :deep(.el-checkbox__input) {
            .el-checkbox__inner {
              border-radius: 6px;
              border-width: 2px;
              width: 18px;
              height: 18px;

              &:hover {
                border-color: #667eea;
              }
            }

            &.is-checked .el-checkbox__inner {
              background-color: #667eea;
              border-color: #667eea;
            }
          }
        }

        .field-info {
          flex: 1;
          min-width: 0;

          .field-name {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
            word-break: break-all;
          }

          .field-key {
            font-size: 12px;
            color: #64748b;
            font-family: 'Monaco', 'Menlo', monospace;
            background: #f1f5f9;
            padding: 2px 6px;
            border-radius: 4px;
            display: inline-block;
          }
        }

        .field-icon {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;

          .check-icon {
            font-size: 18px;
            color: #667eea;
            animation: checkIn 0.3s ease;
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #64748b;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
      }

      .empty-text {
        font-size: 16px;
      }
    }
  }
}

.export-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;

  .footer-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #64748b;
    font-size: 14px;

    i {
      color: #3b82f6;
    }
  }

  .footer-buttons {
    display: flex;
    gap: 12px;

    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 12px 24px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      &.el-button--primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;

        &:hover {
          opacity: 0.9;
        }

        &:disabled {
          background: #e2e8f0;
          color: #94a3b8;
          transform: none;
          box-shadow: none;
        }
      }

      i {
        margin-right: 6px;
      }
    }
  }
}

@keyframes checkIn {
  0% {
    transform: scale(0) rotate(180deg);
    opacity: 0;
  }
  100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .search-wrapper {
    .search-form {
      .action-buttons {
        width: 100%;
        justify-content: center;
        margin-left: 0 !important;
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
  
  .search-wrapper {
    padding: 15px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
    
    .el-form-item {
      width: 100%;
      margin-right: 0;
      
      .el-select {
        width: 100% !important;
      }
      
      .el-input {
        width: 100% !important;
      }
      
      &.action-buttons {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 8px;
        
        .el-button {
          width: 100%;
          margin-right: 0;
        }
      }
    }
  }
  
  .table-card {
    height: calc(100vh - 280px);
  }
  
  .export-content {
    padding: 16px;
    
    .export-toolbar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
      
      .toolbar-left {
        justify-content: center;
      }
    }
    
    .field-list-container {
      .field-grid {
        grid-template-columns: 1fr;
        max-height: 300px;
      }
    }
  }
  
  .export-footer {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    
    .footer-buttons {
      justify-content: center;
      
      .el-button {
        flex: 1;
        max-width: 200px;
      }
    }
  }
}

@media (max-width: 768px) {
  :deep(.export-dialog) {
    width: 95vw !important;
    margin: 5vh auto;
  }

  .export-dialog-header {
    padding: 20px 16px 16px;

    .header-left {
      gap: 12px;

      .header-icon {
        font-size: 24px;
        padding: 10px;
      }

      .header-title {
        font-size: 18px;
      }

      .header-subtitle {
        font-size: 13px;
      }
    }

    .selected-count {
      padding: 6px 12px;
      font-size: 13px;
    }
  }

  .export-content {
    padding: 16px;

    .export-toolbar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
      padding: 12px 16px;

      .toolbar-left {
        justify-content: center;
      }

      .toolbar-right {
        :deep(.el-input) {
          width: 100% !important;
        }
      }
    }

    .field-list-container {
      .field-grid {
        grid-template-columns: 1fr;
        gap: 12px;
        max-height: 300px;
      }

      .field-card {
        padding: 12px;

        .field-card-content {
          gap: 10px;

          .field-info {
            .field-name {
              font-size: 14px;
            }

            .field-key {
              font-size: 11px;
            }
          }
        }
      }
    }
  }

  .export-footer {
    flex-direction: column;
    gap: 12px;
    padding: 16px;

    .footer-info {
      text-align: center;
      font-size: 13px;
    }

    .footer-buttons {
      width: 100%;
      justify-content: center;

      .el-button {
        flex: 1;
        padding: 10px 20px;
      }
    }
  }
}

@media (max-width: 480px) {
  .export-content {
    .field-list-container {
      .field-grid {
        max-height: 250px;
      }
    }
  }
}
</style>
